import base64
import json
import requests


def encode_image(image_path):
    """
    Encodes an image file into a base64 string.
    Args:
        image_path (str): The path to the image file.

    This function opens the specified image file, reads its content, and encodes it into a base64 string.
    The base64 encoding is used to send images over HTTP as text.
    """

    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode("utf-8")


def create_chat_completion( messages, temperature=0.8, max_tokens=4096, top_p=0.8, use_stream=False):
    """
    This function sends a request to the chat API to generate a response based on the given messages.

    Args:
        model (str): The name of the model to use for generating the response.
        messages (list): A list of message dictionaries representing the conversation history.
        temperature (float): Controls randomness in response generation. Higher values lead to more random responses.
        max_tokens (int): The maximum length of the generated response.
        top_p (float): Controls diversity of response by filtering less likely options.
        use_stream (bool): Determines whether to use a streaming response or a single response.

    The function constructs a JSON payload with the specified parameters and sends a POST request to the API.
    It then handles the response, either as a stream (for ongoing responses) or a single message.
    """

    CogViewUrl = "http://10.1.188.13:28531"

    data = {
        "model": "cogvlm2",
        "messages": messages,
        "stream": use_stream,
        "max_tokens": max_tokens,
        "temperature": temperature,
        "top_p": top_p,
    }

    response = requests.post(f"{CogViewUrl}/v1/chat/completions", json=data, stream=use_stream)
    if response.status_code == 200:
        if use_stream:
            # 处理流式响应(这里不用)
            for line in response.iter_lines():
                if line:
                    decoded_line = line.decode('utf-8')[6:]
                    try:
                        response_json = json.loads(decoded_line)
                        content = response_json.get("choices", [{}])[0].get("delta", {}).get("content", "")
                        print(content)
                    except:
                        print("Special Token:", decoded_line)
        else:
            # 处理非流式响应
            decoded_line = response.json()
            content = decoded_line.get("choices", [{}])[0].get("message", "").get("content", "")
            return content
    else:
        print("Error:", response.status_code)
        return "处理异常请联系管理员"


def build_vision_msg(query: str, path: str):
    try:
        # suffix = utils.get_path_suffix(path)
        with open(path, "rb") as file:
            base64_str = base64.b64encode(file.read()).decode('utf-8')
            messages = [{
                "role": "user",
                "content": [
                    {
                        "type": "text",
                        "text": query
                    },
                    {
                        "type": "image_url",
                        "image_url": {
                            # "url": f"data:image/{suffix};base64,{base64_str}"
                            "url": f"data:image/jpeg;base64,{base64_str}"
                        }
                    }
                ]
            }]
            return messages
    except Exception as e:
        print(e)

if __name__ == '__main__':
    question = "请对给定的图片进行描述。"
    img_url = "image/image/aabskedswkyafeylsdvr.jpg"
    message = build_vision_msg(question,img_url)
    print(message)
    answer = create_chat_completion(message, temperature=0.8, max_tokens=4096, top_p=0.8, use_stream=False)
    print(answer)